package logic

import (
	"context"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"math/rand"
	"shop/models"

	"shop/shopRpc/internal/svc"
	"shop/shopRpc/shopRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *shopRpc.UserLoginRequest) (*shopRpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line
	var user models.User
	err := user.FindUser(models.DB, in.Tel)
	if err != nil {
		err = models.DB.Transaction(func(tx *gorm.DB) error {
			user = models.User{
				Username: fmt.Sprintf("user_%d", rand.Intn(10000)),
				Password: in.Password,
				Tel:      in.Tel,
				IsReal:   0,
			}
			err = user.UserAdd(tx)
			if err != nil {
				return errors.New("用户信息注册失败")
			}
			var userReal models.UsersReals
			userReal.UserID = int(user.ID)
			err = userReal.RealAdd(tx)
			if err != nil {
				return errors.New("实名信息添加失败")
			}
			return nil
		})
		if err != nil {
			return nil, err
		}
	}
	if user.Password != in.Password {
		if err != nil {
			return nil, errors.New("密码错误")
		}
	}
	return &shopRpc.UserLoginResponse{
		UserId: int64(user.ID),
	}, nil
}
